import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.SystemColor;
import java.io.*;
import java.lang.*;
import javax.swing.*;

import ij.text.*;
import ij.plugin.frame.*;
import ij.util.*;
import ij.process.*;
import ij.plugin.*;
import ij.*;
import ij.io.*;
import ij.process.*;
import ij.gui.*;




public class Scan_DICOM_info_ extends PlugInFrame implements ActionListener
{
	String dir_ana;
	String dir_thu;
	String str;
	String[] tagnr;
	String[] tagname;
	String resstr;
	JSlider sliderScale;
	JPanel panel;
	JButton buttonAna,buttonCopy,buttonDirAna,buttonDirThumb;
	JTextField textDir,textThumbs;
	JTextArea TAinfo;
	Checkbox checkSD,checkThumb,checkSpec,checkRaw;
	TextWindow tw;
	ImagePlus imp;
	boolean bShow_SD=false,bSpec,bThumb,bRaw; 
	int scale,teller;

	void read_tags()
	{
		try
		{
      			Enumeration e;
      			Properties tags = new Properties();
      			FileInputStream istream=new FileInputStream("tags.ini");
      			tags.load(istream);
      			istream.close();
      			
      			int i=0,n;

      			for (e=tags.propertyNames( );e.hasMoreElements();i++) 
			{ 
				String key = (String) e.nextElement(); 
				String value = tags.getProperty(key ); 
			
			}
			n=i;
			e=tags.propertyNames( );
			tagnr=new String[i];
			tagname=new String[i];
			i=0;
			for (i=0;i<n;i++) 
			{ 
				tagnr[i] = (String) e.nextElement(); 
				tagname[i] = tags.getProperty(tagnr[i]); 
				
			}
			
			Arrays.sort(tagnr);
			for(i=0;i<n;i++)
				tagname[i] = tags.getProperty(tagnr[i]); 
			
      		}
      		catch (Exception e) 
    		{
      			IJ.write("Could not read tags.ini");
      			System.out.println(e);
      			tagnr=new String[0];
			tagname=new String[0];
      		}
	}
	

	public Scan_DICOM_info_()
	{
		super("Scan DICOM info");
		setBackground(SystemColor.control);
		setLayout(new BorderLayout());
		read_tags();
		panel = new JPanel();
		panel.setLayout(new GridLayout(5,3));
		panel.setBackground(SystemColor.control);
		panel.add(new JLabel("Analyse DICOM images in:"));
		textDir=new JTextField("c:\\");
		panel.add(textDir);
		buttonDirAna=new JButton("Choose...");
		buttonDirAna.addActionListener(this);
		panel.add(buttonDirAna);
		panel.add(new JLabel("Create thumbnails and/or raws in :"));
		textThumbs=new JTextField("c:\\");
		panel.add(textThumbs);
		buttonDirThumb=new JButton("Choose...");
		buttonDirThumb.addActionListener(this);
		panel.add(buttonDirThumb);
		checkSD=new Checkbox("Analyse subdirs too",false);
		panel.add(checkSD);
		checkSpec=new Checkbox("Summarize selected data tags only",true);
		panel.add(checkSpec);
		panel.add(new JLabel(""));
		checkRaw=new Checkbox("Extract images as raw",false);
		panel.add(checkRaw);
		checkThumb=new Checkbox("Create thumbnails, rescale factor: ",false);
		panel.add(checkThumb);
		sliderScale=new JSlider(5,40,20);
		sliderScale.setMajorTickSpacing(10);
		sliderScale.setMajorTickSpacing(5);
		sliderScale.setPaintTicks(true);
		sliderScale.setPaintLabels(true);
		panel.add(sliderScale);
		buttonAna = new JButton("Start analysis");
		buttonAna.addActionListener(this);
		panel.add(buttonAna);
		panel.add(new JLabel(""));
		buttonCopy = new JButton("Copy data to system clipboard");
		buttonCopy.addActionListener(this);
		panel.add(buttonCopy);
		add(panel, BorderLayout.NORTH);
		TAinfo=new JTextArea(20,20);
		TAinfo.setEditable(false);
		JScrollPane JSP=new JScrollPane(TAinfo);
		add(JSP,BorderLayout.SOUTH);
		pack();
		show();
	}	

	public void copyData()
	{
			JTextArea TA2=new JTextArea(TAinfo.getText());
			TA2.selectAll();
			TA2.copy();
			return;
	}
	
	public void actionPerformed(ActionEvent e) 
	{
		dir_ana=textDir.getText();
		dir_thu=textThumbs.getText();
		bShow_SD=checkSD.getState();
		bThumb=checkThumb.getState();
		bRaw=checkRaw.getState();
		bSpec=checkSpec.getState();
		scale=sliderScale.getValue();
		
		if (e.getSource() == buttonDirAna)
		{
			JFileChooser fc = new JFileChooser(textDir.getText());
			fc.setDialogTitle("Select a file in the directory to be analysed...");
			int returnVal=fc.showOpenDialog(this);
			if (returnVal == JFileChooser.APPROVE_OPTION) 
			{
		             textDir.setText(fc.getCurrentDirectory().getAbsolutePath());
		             panel.updateUI();
			}
    			return;	
		} 
		
		if (e.getSource() == buttonDirThumb)
		{
			JFileChooser fc = new JFileChooser(textThumbs.getText());
			fc.setDialogTitle("Select a file in the directory for thumbnails/raws...");
			int returnVal=fc.showOpenDialog(this);
			if (returnVal == JFileChooser.APPROVE_OPTION) 
			{
		             textThumbs.setText(fc.getCurrentDirectory().getAbsolutePath());
		             panel.updateUI();
			}
    			return;	
		} 
		
		
		
		if (e.getSource() == buttonAna) 
		{
			Date dt=new Date();
			TAinfo.setText("");
			TAinfo.append("Date and time of analysis: "+dt+"\n");
			if (bSpec)
			{
				TAinfo.append("file\ttype\tsize\t");
				for(int i=0;i<tagnr.length;i++)
					TAinfo.append(tagname[i]+"\t");
				TAinfo.append("\n");
			}
			writedir(dir_ana,dir_thu);
			copyData();		
			return;
		}
		
		if (e.getSource()==buttonCopy)
		{
			copyData();		
			return;
		
		}
	}

	String sl2u(String s)
	{
		s=s.replace(':','_');
		s=s.replace('\\','_');
		return s;		
	}

	public void writedir(String dir1,String dir2)		//show only specific tags
	{
		int i,j;
		Date ds;
		ImagePlus imp,imp2;
		ImageProcessor ip,ip2;
		File f;
	//	IJ.write(dir1+"->"+dir2);
		Opener fop=new Opener();
		String[]list=new File(dir1).list();
		if (list==null) return;	
		for (int i0=0; i0<list.length; i0++) 
		{
			f = new File(dir1+"\\"+list[i0]);
			if (!f.isDirectory()) 
			{
				ds=new Date(f.lastModified());
				imp = fop.openImage(dir1+"\\",list[i0]);
				if (imp!=null)
				{
					ip=imp.getProcessor();	
					str=(String)imp.getProperty("Info");
					if (!bSpec)
					{
			//			TAinfo.append((String)imp.getProperty("Info")+"\n");
						TAinfo.append("file: "+f.toString()+"\n");
						TAinfo.append("type: "+imp.getType()+"\n");
						TAinfo.append("size: "+imp.getWidth()+"x"+imp.getHeight()+"\n");
						TAinfo.append((String)imp.getProperty("Info")+"\n");
					}
					else
					{
						TAinfo.append(f.toString()+"\t");
						TAinfo.append(imp.getType()+"\t");
						TAinfo.append(imp.getWidth()+"x"+imp.getHeight()+"\t");
					
						for(int tn=0;tn<tagnr.length;tn++)
						{	
							i=str.indexOf(tagnr[tn]);
							if (i>0)
							{
								i=str.indexOf(":",i)+1;
								j=str.indexOf((char)10,i);
								resstr=str.substring(i,j);
			//					TAinfo.append(tagname[tn]+"\t"+resstr+"\n");
								TAinfo.append(resstr+"\t");
							}
							else 
			//					TAinfo.append(tagname[tn]+"\t-\n");
								TAinfo.append("-\t");
						}
					}
					if (bRaw)	
					{
						
						ip2=ip.duplicate();
						short[] pixels = (short[])ip2.getPixels();
						int value, byte1, byte2;
						for (int p=0; p<pixels.length; p++) 
						{
							value = pixels[p];
							byte1 = value&0xff;
							byte2 = (value>>8)&0xff;
							pixels[p] = (short)(byte1<<8 | byte2);
						}
						imp2=new ImagePlus("thumb",ip2);
						new FileSaver(imp2).saveAsRaw(dir2+"\\raw_"+sl2u(dir1)+"_"+list[i0]+".raw");
					}							
					if (bThumb)
					{
						ip2=ip.duplicate();
						imp.killProcessor();
						imp.flush();
						ip2=ip2.resize(ip2.getWidth()/scale,ip2.getHeight()/scale);
						ip2=ip2.convertToByte(true);
						imp=new ImagePlus("thumb",ip2);
						new FileSaver(imp).saveAsJpeg(dir2+"\\thumb_"+sl2u(dir1)+"_"+list[i0]+".jpg");
					}


					{
						imp.killProcessor();
						imp.flush();
					}
				}
				else
				{
					TAinfo.append(f.toString()+"\tcould not open");
				
				}	
				TAinfo.append("\n");
				teller++;
			}
			else
				if (bShow_SD)
					writedir(dir1+"\\"+list[i0],dir2);
				else
					TAinfo.append(f.getName()+"\t is a directory\n");
					
						
		}
	}
	
}
